package com.gitee.yannzh.rune.support.crud;

import cn.hutool.core.util.TypeUtil;
import com.gitee.yannzh.rune.support.crud.base.IDefaultService;
import com.google.common.collect.Maps;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Optional;

/**
 * @author yann
 * @description Mp Crud辅助类，管理Service
 * @date 2023-12-21 22:02
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class CrudHelper {

    /**
     * BaseService缓存
     */
    private static final Map<Class<?>, IDefaultService<?, ?>> SERVICE_CONTAINER = Maps.newConcurrentMap();

    /**
     * 动态获取CrudService
     *
     * @param entityClass 实体Class
     * @param <V>         VO泛型
     * @param <E>         实体泛型
     * @param <S>         返回的Service泛型
     * @return 由Spring管理的动态创建的CrudService
     */
    @SuppressWarnings("unchecked")
    public static <V, E, S extends IDefaultService<V, E>> S getCrudService(Class<E> entityClass) {
        IDefaultService<?, ?> crudService = SERVICE_CONTAINER.get(entityClass);
        return (S) Optional.ofNullable(crudService).orElseThrow(
                () -> new RuntimeException(String.format("Cannot find baseService for entity %s",
                        TypeUtil.getTypeArgument(entityClass, 0))));
    }


    public static synchronized <V, E, S extends IDefaultService<E, V>> void putService(Class<E> entityClass, S service) {
        SERVICE_CONTAINER.put(entityClass, service);
    }


}
